package com.muyun.intellij.plugin.background.image.rotation;

import com.intellij.ide.util.PropertiesComponent;
import com.muyun.intellij.plugin.background.image.rotation.ui.Settings;

import java.io.File;

/**
 * @author Allan de Queiroz
 * @date   07/05/17
 */
public class RandomBackgroundTask implements Runnable {
    
    @Override
    public void run() {
        PropertiesComponent prop = PropertiesComponent.getInstance();
        String folder = prop.getValue(Settings.FOLDER);
        String radio = prop.getValue(Settings.RADIO_BUTTON);
        if (null == radio) {
            return;
        }
        String[] radioButton = radio.split(",");
        boolean keepSameImage = prop.getBoolean(Settings.KEEP_SAME_IMAGE);
        String image = null;
        for (int i = 0; i < radioButton.length; i++) {
            String type = radioButton[i];
            if (folder == null || folder.isEmpty()) {
                NotificationCenter.notice("Image folder not set");
                return;
            }
            File file = new File(folder);
            if (!file.exists()) {
                NotificationCenter.notice("Image folder not set");
                return;
            }
            if (i == 0 || !keepSameImage) {
                image = ImagesHandlerSingleton.INSTANCE.getRandomImage(folder);
            }
            if (image == null) {
                NotificationCenter.notice("No image found");
                return;
            }
            if (image.contains(",")) {
                NotificationCenter.notice("Intellij wont load images with ',' character\n" + image);
            }
            String lastImage = prop.getValue(type);
            if (lastImage != null && lastImage.contains(",")) {
                prop.setValue(type, image + lastImage.substring(lastImage.indexOf(",")));
            } else {
                prop.setValue(type, image);
            }
        }
    }

}
